<template>
  <div class="left-panel">
    <LoadingDialog ref="loadingDialog"/>
    <div class="panel-section search-section">
      <label for="estate-search">楼盘搜索</label>
      <div class="search-input-group">
        <v-select
          v-model="selectedOption"
          :options="options"
          :filterable="false"
          :clearable="true"
          @search="onSearch"
          placeholder="输入关键词搜索楼盘..."
          class="search-select"
        >
          <template #no-options>
            <div>输入关键词开始搜索...</div>
          </template>
        </v-select>
      </div>
    </div>
    <div>
      <v-select
        v-model="selectApartment"
        :options="type1List"
        :multiple="true"
        :placeholder="selectedOption ? '请选择 ' + selectedOption.value + ' 的评测户型' : '请先选择楼盘'"
      />
    </div>  
    <div class="panel-section">
      <label for="hotspot-article">热点事件文章内容</label>
      <textarea id="hotspot-article" v-model="hotspotArticle" placeholder="请输入或粘贴相关的文章..."></textarea>
    </div>
    <div class="panel-section">
      <label for="supplementary-material">补充素材</label>
      <textarea id="supplementary-material" v-model="supplementaryMaterial" placeholder="可以输入更多背景资料、数据或引言..."></textarea>
    </div>
    <div class="panel-section">
              <label for="generated-summary">生成价值点框架</label>
        <textarea id="generated-summary" v-model="generatedContent" @input="handleTextareaChange" placeholder="此处将显示生成的价值点内容..."></textarea>
        <div class="button-group">
          <button @click="generateContent" class="action-button">生成框架旧</button>
          <button @click="generateContentNew" class="action-button new-button">生成框架新</button>
        </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import vSelect from 'vue-select';
import axios from 'axios';
import LoadingDialog from './LoadingDialog.vue';

const loadingDialog = ref(null);
const selectedOption = ref(null);
const options = ref([]);
const type1List = ref([])
const selectApartment = ref([]) 

const onSearch = (search, loading) => {
  if (search.length) {
    loading(true);
    axios.post('/formal/erp/ai/get/searchEstateName', {
      search: search
    })
    .then(response => {
      if (response.data && Array.isArray(response.data.data)) {
        options.value = response.data.data.map(item => ({
          label: item.real_estate_name + '(' + item.type + ')', // Use estateName for display
          id: item.id,
          type: item.type,
          value: item.real_estate_name
        }));
      } else {
        options.value = [];
      }
    })
    .catch(error => {
      console.error("API call failed:", error);
      options.value = [];
    })
    .finally(() => {
      loading(false);
    });
  }
};

// const onEstateSelected = (value) => {
//   console.log('onEstateSelected triggered with:', value);
//   console.log('current selectedOption:', selectedOption.value);
  
//   // 确保有有效的选择
//   if (selectedOption.value && selectedOption.value.id) {
//     console.log('Proceeding with search for:', selectedOption.value.label);
//     type1List.value = [];
//     search();
//   } else {
//     console.log('No valid selection found');
//   }
// };

// 添加 watch 监听器来确保每次选择都能触发
watch(selectedOption, (newValue, oldValue) => {
  console.log('selectedOption changed:', newValue, 'from:', oldValue);
  if (newValue && newValue.id) {
    type1List.value = [];
    search();
  }
}, { deep: true });

const hotspotArticle = ref('');
const supplementaryMaterial = ref('');
const generatedContent = ref('');

const search = () => {
  console.log('search function called with selectedOption:', selectedOption.value);
  if (selectedOption.value) {
    axios.post('/api/erp/get/latest/estate/label', {
      estate_id: selectedOption.value.id,
      type: 'apartment'
    })
    .then(res => {
      type1List.value = [];
      let labelData = res.data.labels || [];
      labelData.map((item) => {
        if (item.serial_number && item.square) {
          type1List.value.push(item.square + "㎡ " + item.serial_number);
        }
      });
      type1List.value = Array.from(new Set(type1List.value));

    })
    .catch(error => {
      console.log("API call failed:", error);
      type1List.value = [];
    })
    .finally(() => {
      console.log('Search finished.');
    });

    window.localStorage.clear()
    console.log('selectedOption.value.type:', selectedOption.value.type);
    window.localStorage.setItem('estate_type', selectedOption.value.type);


    axios.post('/media/predict/test/get/estate/history/article', { estate_id: selectedOption.value.id })
    .then(res => {

      let history = res.data.res
      window.localStorage.setItem('generationHistory', JSON.stringify(history));

      window.dispatchEvent(new CustomEvent('history-updated'));

    }).catch(error => {
      console.log("API history failed:", error);
      type1List.value = [];
    }).finally(() => {
      console.log('history finished.');
    });

  } else {
    alert('请先选择对应楼盘！！！');
  }
};

const handleTextareaChange = () => {
    console.log('内容变化了:', generatedContent.value);
    window.localStorage.setItem('supplementaryMaterial', generatedContent.value);
}

const reviewContent = ref({});

const generateContent = () => {
  if (selectedOption.value) {
    loadingDialog.value.show('正在生成价值点，请稍候...');
    let params = {
      estate_name: selectedOption.value.value,
      estate_id: selectedOption.value.id,
      market: hotspotArticle.value,
      base_info: supplementaryMaterial.value,
      apartments: []
    }
    if (selectApartment.value.length > 0) {
        for (let item of selectApartment.value) {
          let arr = item.split('㎡ ');
          let apartment = {
            square: parseFloat(arr[0]),
            serial_number: arr[1]
          }
          params.apartments.push(apartment);
        }
    }

    axios.post('/media/predict/test/get/opinion/by/estate', params, {
      timeout: 90000 // 设置30秒超时
    })
      .then(res => {
        let data = res.data.res
        reviewContent.value = data.data
        reviewContent.value.estate_name = selectedOption.value.value
        reviewContent.value.estate_id = selectedOption.value.id
        reviewContent.value.hot_content = hotspotArticle.value
        reviewContent.value.other_info = supplementaryMaterial.value
        reviewContent.value.opinions = data.opinions.res
        window.localStorage.setItem('reviewContent', JSON.stringify(reviewContent.value));
        window.localStorage.setItem('supplementaryMaterial', data.opinions.res);
        generatedContent.value = data.opinions.res;
      })
      .catch(error => {
        console.log("API call failed:", error);
        if (error.code === 'ECONNABORTED') {
          alert('请求超时，请重试');
        } else {
          alert('生成价值点失败，请重试');
        }
      })
      .finally(() => {
        loadingDialog.value.hide();
        console.log('Search finished.');
      });
  } else {
    alert('请先选择对应楼盘！！！');
  }
};

const generateContentNew = () => {
  if (selectedOption.value) {
    loadingDialog.value.show('正在生成新框架价值点，请稍候...');
    let params = {
      estate_name: selectedOption.value.value,
      estate_id: selectedOption.value.id,
      market: hotspotArticle.value,
      base_info: supplementaryMaterial.value,
      type: 'new',
      apartments: []
    }
    if (selectApartment.value.length > 0) {
        for (let item of selectApartment.value) {
          let arr = item.split('㎡ ');
          let apartment = {
            square: parseFloat(arr[0]),
            serial_number: arr[1]
          }
          params.apartments.push(apartment);
        }
    }

    axios.post('/media/predict/test/get/opinion/by/estate', params, {
      timeout: 200000 // 设置200秒超时
    })
      .then(res => {
        let data = res.data.res
        reviewContent.value = data.data
        reviewContent.value.estate_name = selectedOption.value.value
        reviewContent.value.estate_id = selectedOption.value.id
        reviewContent.value.hot_content = hotspotArticle.value
        reviewContent.value.other_info = supplementaryMaterial.value
        reviewContent.value.opinions = data.opinions.res
        window.localStorage.setItem('reviewContent', JSON.stringify(reviewContent.value));
        window.localStorage.setItem('supplementaryMaterial', data.opinions.res);
        generatedContent.value = data.opinions.res;
      })
      .catch(error => {
        console.log("API call failed:", error);
        if (error.code === 'ECONNABORTED') {
          alert('请求超时，请重试');
        } else {
          alert('生成新框架价值点失败，请重试');
        }
      })
      .finally(() => {
        loadingDialog.value.hide();
        console.log('New framework generation finished.');
      });
  } else {
    alert('请先选择对应楼盘！！！');
  }
};
</script>

<style scoped>
.left-panel {
  width: 40%;
  min-width: 500px; /* 避免在小屏幕上被过度挤压 */
  max-width: 650px;
  padding: 40px;
  display: flex;
  flex-direction: column;
  gap: 25px; /* 调整区域间的垂直间距 */
  border-right: 1px solid var(--border-color, #EAEAEA);
  background-color: var(--panel-bg-color, #fff);
  overflow-y: auto;
}

.panel-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}



.search-section {
  flex-direction: column;
  gap: 10px;
}

.search-input-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-select {
  flex: 1;
}

.selected-estate-display {
  font-size: 0.85em;
  color: #666;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 10px;
}



/* vue-select override styles */
:deep(.search-select .vs__dropdown-toggle) {
  height: 45px;
  padding: 0.4em 0.7em;
  border-radius: 8px;
  border: 1px solid var(--border-color);
  background-color: var(--panel-bg-color);
  transition: all 0.3s ease;
}

:deep(.search-select.vs--open .vs__dropdown-toggle) {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(253, 216, 53, 0.4);
}

:deep(.search-select .vs__search::placeholder) {
  color: #aaa;
}

:deep(.search-select .vs__dropdown-menu) {
  border: 1px solid var(--border-color);
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.search-select .vs__dropdown-option) {
  padding: 10px 15px;
  transition: background-color 0.2s ease;
}

:deep(.search-select .vs__dropdown-option--highlight) {
  background-color: var(--primary-color);
  color: #333;
}

label {
  font-weight: 600; /* 加粗标签文本 */
  font-size: 1em;
}

textarea {
  min-height: 120px; /* 为所有文本框设置一个最小高度 */
  resize: vertical;
}

#hotspot-article {
  height: 250px;
  resize: vertical;
}

#supplementary-material {
  height: 250px;
  resize: vertical;
}

#generated-summary {
  background-color: #fafafa;
  color: #555;
  white-space: pre-wrap;
  font-family: inherit;
  line-height: 1.6;
  padding: 15px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  height: 800px;
  resize: vertical;
  transition: all 0.3s ease;
}

#generated-summary:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(253, 216, 53, 0.2);
  outline: none;
}

#generated-summary::placeholder {
  color: #999;
  font-style: italic;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.action-button {
  flex: 1;
  background-color: var(--primary-color);
  color: #333;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-button:hover {
  background-color: var(--secondary-color);
  transform: translateY(-1px);
}

.action-button:active {
  transform: translateY(0);
}

.new-button {
  background-color: #4CAF50;
  color: white;
}

.new-button:hover {
  background-color: #45a049;
}
</style> 